import axios from 'axios'
import authUtils from './auth'

// 创建axios实例
const api = axios.create({
  baseURL: 'http://127.0.0.1:8000/api',
  timeout: 10000,
  withCredentials: false, // 禁用Cookie跨站传输
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
    'X-Requested-With': 'XMLHttpRequest'
  }
})

// 请求拦截器
api.interceptors.request.use(
  config => {
    // 添加token到请求头
    const token = localStorage.getItem('token') || localStorage.getItem('adminToken')
    console.log('Axios请求拦截器 - 获取到的token:', token)
    console.log('请求URL:', config.url)
    
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
      console.log('已添加Authorization头:', config.headers.Authorization)
    } else {
      console.log('未找到token，请求将不带认证头')
    }
    
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    console.error('API Error:', error.response?.data || error.message)
    
    // 处理401未授权错误
    if (error.response?.status === 401) {
      authUtils.logout()
    }
    
    return Promise.reject(error)
  }
)

export default api


